package com.school.movie.business.web.controller;

import com.school.movie.business.web.model.vo.AreaVo;
import com.school.movie.business.web.model.vo.MovieTypeVo;
import com.school.movie.business.web.model.vo.MovieVo;
import com.school.movie.business.web.model.vo.MovieYearVo;
import com.school.movie.common.model.BaseResponse;
import com.school.movie.common.model.ResultCode;
import com.school.movie.common.utils.BaseConstants;
import com.school.movie.common.utils.MediaUtil;
import com.school.movie.common.bean.PageBean;
import com.school.movie.service.imp.MovieServiceImpl;
import com.school.movie.service.imp.SysLogServiceImp;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Objects;
import java.util.UUID;

@Controller
@RequestMapping("/movie")
public class MovieController {

    @Autowired
    MovieServiceImpl movieService;
    @Autowired
    SysLogServiceImp logService;
    @Value("${upload.absPath}")
    String absPath;
    @Value("${nginx.video.path}")
    String videoPath;


    @RequestMapping("/list")
    public String list(MovieVo movie, PageBean pager, HttpSession session, ModelMap map) {
        if (movie == null || movie.getMovieName() == null) {
            if (session.getAttribute("movie") != null) {
                movie = (MovieVo) session.getAttribute("movie");
            }
        } else {
            session.setAttribute("movie", movie);
        }
        getParams(movie, pager, map);
        return "movie";
    }

    /**
     * 添加电影
     *
     * @param session
     * @param file1
     * @param movie
     * @param map
     * @return
     * @throws Exception
     */
    @PostMapping("/save")
    public String save(HttpSession session, MultipartFile file1, MovieVo movie, ModelMap map) throws Exception {
        if (movie.getMovieId() > 0) {
            MovieVo g = movieService.getById(movie.getMovieId());
            if (Objects.equals(file1.getOriginalFilename(), "")) {
                movie.setCimg(g.getCimg());
            } else {
                String picName = UUID.randomUUID().toString();
                // 截取文件的扩展名(如.jpg)
                String oriName = file1.getOriginalFilename();
                System.out.println("--上传文件名-->>" + oriName);
                String extName = oriName.substring(oriName.lastIndexOf("."));

                String newFileName = picName + extName;
                File targetFile = new File(absPath, newFileName);
                // 保存文件
                file1.transferTo(targetFile);
                movie.setCimg("card/" + newFileName);
            }
            movieService.update(movie);
            logService.add(BaseConstants.LOG_UPDATE, movie.toString());
        } else {
            if (Objects.equals(file1.getOriginalFilename(), "")) {
                movie.setCimg("");
            } else {
                String picName = UUID.randomUUID().toString();
                // 截取文件的扩展名(如.jpg)
                String oriName = file1.getOriginalFilename();
                System.out.println("--上传文件名-->>" + oriName);
                String extName = oriName.substring(oriName.lastIndexOf("."));

                String newFileName = picName + extName;
                File targetFile = new File(absPath, newFileName);
                // 保存文件
                file1.transferTo(targetFile);
                movie.setCimg("card/" + newFileName);
            }
            movieService.add(movie);
            logService.add(BaseConstants.LOG_ADD, movie.toString());
        }
        movie = new MovieVo();
        if (session.getAttribute("movie") != null) {
            movie = (MovieVo) session.getAttribute("movie");
        }
        map = getParams(movie, new PageBean(), map);
        return "movie";
    }

    private ModelMap getParams(MovieVo movie, PageBean pager, ModelMap map) {
        int cnt = movieService.count(movie);
        pager.setTotalRows(cnt);
        List<MovieVo> movieList = movieService.list(movie, pager);
        pager.setData(movieList);
        List<AreaVo> areaList = movieService.areaList();
        List<MovieYearVo> yearList = movieService.yearList();
        List<MovieTypeVo> movieTypeList = movieService.movieTypeList();

        map.addAttribute("pager", pager);
        map.addAttribute("movie", movie);
        map.addAttribute("areaList", areaList);
        map.addAttribute("yearList", yearList);
        map.addAttribute("movieTypeList", movieTypeList);
        return map;
    }

    /**
     * 跳转电影添加面板，用于数据回显
     *
     * @param map
     * @return
     */
    @RequestMapping("/add")
    public String add(ModelMap map) {
        List<AreaVo> areaList = movieService.areaList();
        List<MovieYearVo> yearList = movieService.yearList();
        List<MovieTypeVo> movieTypeList = movieService.movieTypeList();
        MovieVo movie = new MovieVo();
        movie.setMovieId(0);
        map.addAttribute("areaList", areaList);
        map.addAttribute("yearList", yearList);
        map.addAttribute("movieTypeList", movieTypeList);
        map.addAttribute("movie", movie);
        return "movieAdd";
    }

    /**
     * 更新电影信息
     *
     * @param movie
     * @param map
     * @return
     */
    @RequestMapping("/update")
    public String update(MovieVo movie, ModelMap map) {
        movie = movieService.getById(movie.getMovieId());
        List<AreaVo> areaList = movieService.areaList();
        List<MovieYearVo> yearList = movieService.yearList();
        List<MovieTypeVo> movieTypeList = movieService.movieTypeList();
        map.addAttribute("movie", movie);
        map.addAttribute("areaList", areaList);
        map.addAttribute("yearList", yearList);
        map.addAttribute("movieTypeList", movieTypeList);

        return "movieAdd";
    }


    /**
     * 删除电影信息
     *
     * @param ids
     * @param map
     * @return
     */
    @RequestMapping("/del")
    public String del(String ids, ModelMap map) {
        String[] arr = ids.split(",");
        movieService.del(arr);
        getParams(new MovieVo(), new PageBean(), map);
        return "movie";
    }

    /**
     * 上传视频,存到nginx存放视频文件的目录
     */
    @PostMapping("uploadVideo")
    public BaseResponse<Object> uploadVideo(
            @RequestParam("mid") String mid,
            @RequestParam("movieID") Integer movieId,
            MultipartFile file
    ) throws IOException {
        if (!MediaUtil.isVideo(file)){
            return BaseResponse.builders(ResultCode.FAILURE,null);
        }
        //保存视频文件到指定路径
        file.transferTo(new File(videoPath));

        return BaseResponse.builders(ResultCode.SUCCESS,null);
    }


}
